import util from '../../utils/util';

const app = getApp()

Page({
    data: {
		TabCur: 1,
		scrollLeft:0,
		statusList:{'0':'已申请','1':'已通过', '2':'被驳回'},
		typeList:[],
		index:0,
		typeId:0,
		durType:'D',
		startTimeReal:null,
		endTimeReal:null,
		leaveTeaList:[],
		pageNum: 1, // 当前页码
		pageSize: 10, // 每页数量
		orderBy: 'create_time desc',
		hasMore: true // 是否还有更多数据
    },
    tabSelect(e) {
		var curTab = e.currentTarget.dataset.id;
		this.setData({
		  TabCur: curTab,
		  scrollLeft: (e.currentTarget.dataset.id-1)*60
		});
		if(curTab == 2) {
			this.loadApplyInfos();
		}
    },
    onLoad(options) {
		this.setData({
			teacherInfo : wx.getStorageSync('teacheruserInfo')
		});
		this.loadTypeList();
		//this.loadApplyInfos();
		if(options.tabNum) {
			this.setData({
				TabCur : options.tabNum
			});
			if(options.tabNum == 2) {
				this.loadApplyInfos();
			}
		}
	},
	onReachBottom() {
		var that = this;
		if(this.data.hasMore) {
			that.data.pageNum++;
			this.loadApplyInfos();
		}
		
	},
	onShow(){
	  var that = this;
	  //验证码
	  this.createCode();
	},
	
	loadTypeList() {
		var that = this;
		var tl = [], tlObj = {};
		util.get(`listDictData?dictType=manage_leave_type`,response=>{
		  if (response.code == 0) {
			  tl = response.data;
			  for(var i=0;i<tl.length;i++) {
				  tlObj[tl[i].dictValue] = tl[i];
			  }
			  that.setData({
				  tlObj: tlObj,
				  typeList: tl
			  });
		  } else {
			  wx.showToast({
			    title: response.msg,
			    icon: 'none',
			    duration: 2000
			  }) 
		  }
		})
	},
	typeChange(e) {
		var dictValue = this.data.typeList[e.detail.value].dictValue;
		console.log('请假类型改变，值为：', dictValue);
		this.setData({
			typeId: dictValue,
			index: e.detail.value
		})
   },
   startDateChange(e) {
   		var startDate = e.detail.value;
   		this.setData({
   			startDate: startDate
   		})
   },
   endDateChange(e) {
   		var endDate = e.detail.value;
   		this.setData({
   			endDate: endDate
   		})
   },
   startTimeChange(e) {
   		var startTime = e.detail.value;
   		this.setData({
   			startTime: startTime
   		})
   },
   endTimeChange(e) {
   		var endTime = e.detail.value;
   		this.setData({
   			endTime: endTime
   		})
   },
   
   radioChange(e) {
   		var durType = e.detail.value;
   		this.setData({
   			durType: durType
   		})
   },
  
  //提交请假单
  confrimApply:function(e){
    wx.showLoading({title: '请稍后...'})
    var that = this;
	const {typeId, durType, startDate, endDate, startTime, endTime, teacherInfo} = that.data;
	var inputcaptchacode = e.detail.value.inputcaptchacode;
	var reason = e.detail.value.reason;
	var duration = e.detail.value.duration;
	
    if (typeId == null || typeId == -1) {
      wx.showToast({
        title: '请选择请假类型',
        icon: 'error', 
        duration: 2000
      })
      return false;
    }
	if (duration == null || duration <=0 || !(/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(duration))) {
	  wx.showToast({
	    title: '请检查请假时长',
	    icon: 'error', 
	    duration: 2000
	  })
	  return false;
	}
	
	if(!startDate || !endDate || !startTime || !endTime) {
		wx.showToast({
		  title: '请检查请假时间',
		  icon: 'error', 
		  duration: 3000
		})
		return false;
	}
	//拼凑Date和Time
	var startTimeReal = startDate + ' ' + startTime;
	var endTimeReal = endDate + ' ' + endTime;
	
	if((new Date(startTimeReal))>(new Date(endTimeReal))) {
		wx.showToast({
		  title: '请假开始时间不能大于结束时间',
		  duration: 3000
		})
		return false;
	}
	
    if(inputcaptchacode.length==0){
      wx.showToast({
        title: '请输入验证码',
        icon: 'error',
        duration: 2000
      })
      return false;
    }
    if(('' + inputcaptchacode).toUpperCase()!=this.data.captchacode.toUpperCase()){
      wx.showToast({
        title: '验证码不正确',
        icon: 'error',
        duration: 2000
      })
      this.nextCode();
    }else{
      let params = {};
	  params.leaverId = teacherInfo.userId;
      params.type = typeId; //
      params.duration = duration; //
	  params.durType = durType;
	  params.reason = reason;
	  params.startTime = startTimeReal;
	  params.endTime = endTimeReal;
      util.post('leave/addLeaveTea',params,response=>{
        const data = response;
        if (data.code === 0) {
          console.log("----报名成功----",data)
         
          wx.hideLoading() //关闭提示框
          wx.showToast({
            title: '填写请假单成功',
            icon: 'scuess', 
            duration: 2000
          });
		  //为了清空form，重新跳转到此页面，并直接切换到请假列表标签
		  wx.navigateTo({
		    url:'/pages/leaveTea/index?tabNum=2'
		  });
        }else{
          wx.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      })
  	}
  },
  loadApplyInfos() {
	  var that = this;
	  var leaveTeaList = this.data.leaveTeaList;
	  util.get(`leave/listLeaveTea?leaverId=${that.data.teacherInfo.userId}&pageNum=${that.data.pageNum}&pageSize=${that.data.pageSize}&orderBy=${that.data.orderBy}`,response=>{
	    // TIPS: 为0不一般是失败么
	    if (response.code == 0) {
			wx.showToast({title: '加载中...',icon: 'loading',duration:1000});
			leaveTeaList = leaveTeaList.concat(response.data);
	        that.setData({
	  		  leaveTeaList: leaveTeaList
	  	  });
		  if(leaveTeaList.length >= response.total) {
			  that.setData({
				  hasMore: false
			  });
		  }
	    } else {
	  	  wx.showToast({
	  	    title: response.msg,
	  	    icon: 'none',
	  	    duration: 2000
	  	  }) 
	    }
	  })
  },
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },
  
  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },
  
  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection =='left'){
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  deleteLeave(e){
	  var leaId = e.currentTarget.dataset.id;
	  var status = e.currentTarget.dataset.status;
      if(status == '1') {
		  wx.showToast({
		    title: '已无法删除！',
		    icon: 'none',
		    duration: 2000
		  });
	  } else {
		  wx.showLoading({title: '请稍后...'})
		  var params = {'id':leaId};
		  util.post('leave/remove',params,response=>{
			wx.hideLoading()//关闭提示框
		    const data = response;
		    if (data.code === 0) {
		      wx.showToast({
		        title: '删除请假单成功',
		        icon: 'scuess', 
		        duration: 2000
		      });
		  		  //为了清空form，重新跳转到此页面，并直接切换到请假列表标签
		  		  wx.navigateTo({
		  		    url:'/pages/leaveTea/index?tabNum=2'
		  		  });
		    }else{
		      wx.showToast({
		        title: data.msg,
		        icon: 'none',
		        duration: 2000
		      })
		    }
		  });
	  }
  },
  //验证码切换
  nextCode(){
    this.createCode()
  },
  //创建验证码
  createCode() {
    var code;
    //首先默认code为空字符串
    code = '';
    //设置长度，这里看需求，我这里设置了4
    var codeLength = 4;
    //设置随机字符
    var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
    //循环codeLength 我设置的4就是循环4次
    for (var i = 0; i < codeLength; i++) {
      //设置随机数范围,这设置为0 ~ 36
      var index = Math.floor(Math.random() * 62);
      //字符串拼接 将每次随机的字符 进行拼接
      code += random[index];
    }
    //将拼接好的字符串赋值给展示的code
    this.setData({
      captchacode: code
    })
  }
})
